﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Actya.Web.Mvc
{
	public class MultiDependencyResolver : IDependencyResolver
	{
		private readonly List<IDependencyResolver> _innerResolvers;

		public MultiDependencyResolver(IEnumerable<IDependencyResolver> innerResolvers)
		{
			_innerResolvers = new List<IDependencyResolver>(innerResolvers);
		}

		public object GetService(Type serviceType)
		{
			foreach (var dependencyResolver in _innerResolvers)
			{
				var service = dependencyResolver.GetService(serviceType);
				if (service != null)
				{
					return service;
				}
			}
			return null;
		}

		public IEnumerable<object> GetServices(Type serviceType)
		{
			foreach (var dependencyResolver in _innerResolvers)
			{
				var services = dependencyResolver.GetServices(serviceType);
				if (services != null && services.Any())
				{
					return services;
				}
			} 
			return new IDependencyResolver[] {};
		}

		public void AddResolver(IDependencyResolver resolver)
		{
			if (resolver == null)
			{
				throw new ArgumentNullException("resolver", "The resolver to add may not be null.");
			}
			this._innerResolvers.Add(resolver);
		}
	}
}
